import { ref } from 'vue'

// 定义在线统计信息类型
interface OnlineStats {
  onlineCount: number
  timestamp: number
}

// 使用 ref 创建响应式数据
export const onlineUserCount = ref<number>(0)
export const isConnected = ref<boolean>(false)

let websocket: WebSocket | null = null
let reconnectInterval: number | null = null
let pingInterval: number | null = null

// WebSocket连接地址 (通过环境变量配置)
const websocketUrl = `${import.meta.env.VITE_WEBSOCKET_URL}/user/ws/online`

/**
 * 初始化WebSocket连接
 */
export function initWebSocket() {
  if (websocket && websocket.readyState === WebSocket.OPEN) {
    return
  }

  try {
    websocket = new WebSocket(websocketUrl)
    
    websocket.onopen = () => {
      console.log('WebSocket连接已建立')
      isConnected.value = true
      
      // 启动心跳机制
      startHeartbeat()
    }
    
    websocket.onmessage = (event) => {
      try {
        const data: OnlineStats = JSON.parse(event.data)
        onlineUserCount.value = data.onlineCount
        console.log('在线用户数更新:', data.onlineCount)
      } catch (error) {
        console.error('解析WebSocket消息失败:', error)
      }
    }
    
    websocket.onclose = () => {
      console.log('WebSocket连接已关闭')
      isConnected.value = false
      stopHeartbeat()
      
      // 尝试重连
      reconnect()
    }
    
    websocket.onerror = (error) => {
      console.error('WebSocket连接错误:', error)
      isConnected.value = false
      stopHeartbeat()
    }
  } catch (error) {
    console.error('WebSocket连接初始化失败:', error)
    reconnect()
  }
}

/**
 * 发送心跳包
 */
function sendPing() {
  if (websocket && websocket.readyState === WebSocket.OPEN) {
    websocket.send('ping')
  }
}

/**
 * 启动心跳机制
 */
function startHeartbeat() {
  stopHeartbeat()
  pingInterval = window.setInterval(sendPing, 60000) // 每30秒发送一次心跳
}

/**
 * 停止心跳机制
 */
function stopHeartbeat() {
  if (pingInterval) {
    clearInterval(pingInterval)
    pingInterval = null
  }
}

/**
 * 重连机制
 */
function reconnect() {
  if (reconnectInterval) {
    return
  }
  
  reconnectInterval = window.setTimeout(() => {
    console.log('尝试重新连接WebSocket...')
    initWebSocket()
    reconnectInterval = null
  }, 5000) // 5秒后重试
}

/**
 * 关闭WebSocket连接
 */
export function closeWebSocket() {
  if (websocket) {
    websocket.close()
    websocket = null
  }
  
  stopHeartbeat()
  
  if (reconnectInterval) {
    clearTimeout(reconnectInterval)
    reconnectInterval = null
  }
}